﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using FixSoft.CloudGround.Base;
using FixSoft.Tools.Common;
using Microsoft.VisualBasic.Devices;
using FixSoft.Tools.ETaskDialog;
using FixSoft.Tools.TaskDialogTools;

namespace FixSoft.CloudGround
{
    /// <summary>
    /// Interaction logic for Options.xaml
    /// </summary>
    public partial class Options : Window
    {
        public event EventHandler UpdateSettings;
        private readonly List<string> langCodes = new List<string>();
        public Options()
        {
            InitializeComponent();
        }

        private void WindowSourceInitialized(object sender, EventArgs e)
        {
            var handle = new WindowInteropHelper(this).Handle;

            var margins = new WinAPI.Margins { cyTopHeight = 34 };

            HwndSource.FromHwnd(handle).CompositionTarget.BackgroundColor = Color.FromArgb(0, 0, 0, 0);

            Dwm.ExtendGlassFrame(handle, ref margins);

            var fileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location);
            BuildTag.Text = Assembly.GetExecutingAssembly().GetName().Version + ".beta." + fileInfo.LastWriteTimeUtc.ToString("yyMMdd-HHmm");

            if (!string.IsNullOrEmpty(App.Settings.Search))
                SearchBox.Text = App.Settings.Search;
            switch ((int)App.Settings.TimeMode)
            {
                case 1000:
                    IMComboBox.SelectedIndex = 0;
                    break;
                case 60000:
                    IMComboBox.SelectedIndex = 1;
                    break;
                case 3600000:
                    IMComboBox.SelectedIndex = 2;
                    break;
            }
            AutoDownloadCheckBox.IsChecked = App.Settings.DownloadAutomatically;
            if (App.Settings.RefreshInterval != 1)
                RefreshIntervalSlider.Value = App.Settings.RefreshInterval;
            else
                RefreshIntervalSlider.Value = 0;
            SkipLowResCheckBox.IsChecked = App.Settings.SkipLowRes;
            GetMaxResCheckBox.IsChecked = App.Settings.GetMaxRes;
            ShowWarningCheckBox.IsChecked = App.Settings.ShowWarning;
            LaunchOnStartUpCheckBox.IsChecked = StartUp.IsProgramOnStartUp();
            LanguageComboBox.Items.Add(new ComboBoxItem() { Content = CultureInfo.GetCultureInfo("en-US").NativeName });
            langCodes.Add("en-US");
            var langs = from x in Directory.GetDirectories(App.Path) where x.Contains("-") select System.IO.Path.GetFileNameWithoutExtension(x);
            foreach (var l in langs)
            {
                try
                {
                    var c = CultureInfo.GetCultureInfo(l);
                    langCodes.Add(c.Name);
                    LanguageComboBox.Items.Add(new ComboBoxItem() { Content = c.NativeName });
                }
                catch { }
            }

            LanguageComboBox.Text = CultureInfo.GetCultureInfo(App.Settings.Language).NativeName;

            ClearCacheCheckBox.IsChecked = App.Settings.ClearOldPics;
            ClearIntervalSlider.Value = App.Settings.ClearInterval;

            FilterBox.Text = App.Settings.Filter;

            if (Environment.OSVersion.Version.Major < 6 || Environment.OSVersion.Version.Minor < 1)
                ChangeLogonBgCheckBox.Visibility = System.Windows.Visibility.Collapsed;
            ChangeLogonBgCheckBox.IsChecked = App.Settings.ChangeLogonBg;

            // if (App.Settings.Language != "ru-RU")
            //  {
            // FilterPanel.Visibility = System.Windows.Visibility.Collapsed;
            // }


            if (App.PictureManager != null && App.PictureManager.Providers != null)
            {
                foreach (var p in App.PictureManager.Providers)
                {
                    ProvidersBox.Items.Add(p.Name);
                }
                ProvidersBox.SelectedIndex = App.PictureManager.Providers.IndexOf(App.PictureManager.CurrentProvider);
            }

            ApplyButton.IsEnabled = false;
        }

        private void OkButtonClick(object sender, RoutedEventArgs e)
        {
            bool IsS = true;
            if (ApplyButton.IsEnabled)
            {
                IsS = ApplySettings();
                if (IsS)
                    ApplyButton.IsEnabled = false;
            }
            if (IsS)
                this.Close();
        }

        private void CancelButtonClick(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void ApplyButtonClick(object sender, RoutedEventArgs e)
        {
            ApplySettings();
            ApplyButton.IsEnabled = false;
        }

        private bool ApplySettings()
        {
            if (SearchBox.Foreground == Brushes.Gray)
            {
               // System.Windows.Forms.Application.EnableVisualStyles();
                ETaskDialog Td = new ETaskDialog(new WindowInteropHelper(this).Handle);
                Td.MainInstruction = "Keyword is not specified";
                Td.Content = "Search keyword is not specified.";
                Td.Buttons = TaskDialogButton.OK;
                Td.CommonIcon = TaskDialogIcon.Warning;
                List<DialogButton> Rb = new List<DialogButton>();
                Rb.Add(new DialogButton(20, "Change keyword to default."));
                Rb.Add(new DialogButton(21, "I'll set it now."));
                Td.RadioButtons = Rb.ToArray();
                //Td.ForceEmulationMode = true;
                Td.Title = System.Windows.Forms.Application.ProductName;
                Results r = Td.Show();
                if (r.RadioID == 20)
                {
                    SearchBox.Text = App.GetDefaultKeyword();
                }
                else
                {
                    return false;
                }
            }
            //if (App.Settings.Search != SearchBox.Text)
            //    App.Translator.Result = string.Empty;
            if (LaunchOnStartUpCheckBox.IsChecked == true)
            {
                if (StartUp.IsProgramOnStartUp() != true)
                {
                    StartUp Su;
                    Su = new StartUp(false);
                    Su.Add();
                }
            }
            else
            {
                StartUp.Remove();
            }
            App.Settings.Search = SearchBox.Text;
            App.Settings.TimeMode = (TimeModes)Enum.Parse(typeof(TimeModes), (string)((ComboBoxItem)IMComboBox.SelectedValue).Content);
            App.Settings.DownloadAutomatically = (bool)AutoDownloadCheckBox.IsChecked;
            App.Settings.GetMaxRes = (bool)GetMaxResCheckBox.IsChecked;
            App.Settings.ShowWarning = (bool)ShowWarningCheckBox.IsChecked;
            App.Settings.SkipLowRes = (bool)SkipLowResCheckBox.IsChecked;
            App.Settings.ClearOldPics = (bool)ClearCacheCheckBox.IsChecked;
            App.Settings.ClearInterval = (int)ClearIntervalSlider.Value;
            App.Settings.Filter = FilterBox.Text;
            if (!string.IsNullOrEmpty(ProvidersBox.Text))
                App.Settings.Provider = ProvidersBox.Text;

            if (RefreshIntervalSlider.Value > 0)
                App.Settings.RefreshInterval = RefreshIntervalSlider.Value;
            else
                App.Settings.RefreshInterval = 1;

            if (LanguageComboBox.SelectedIndex >= 0)
                App.Settings.Language = langCodes[LanguageComboBox.SelectedIndex];

            if (App.Settings.ChangeLogonBg != (bool)ChangeLogonBgCheckBox.IsChecked)
            {
                App.Settings.ChangeLogonBg = (bool)ChangeLogonBgCheckBox.IsChecked;
                //HKLM\Software\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\Background
                if (App.Settings.ChangeLogonBg)
                {
                    var p = new ProcessStartInfo { Verb = "runas", FileName = Assembly.GetExecutingAssembly().Location, Arguments = "/enableoembg" };
                    Process.Start(p);
                }
                else
                {
                    var p = new ProcessStartInfo { Verb = "runas", FileName = Assembly.GetExecutingAssembly().Location, Arguments = "/disableoembg" };
                    Process.Start(p);
                }
            }

            if (App.PictureManager != null && App.PictureManager.Providers != null)
                foreach (Provider p in App.PictureManager.Providers)
                {
                    if (p.Name == App.Settings.Provider)
                    {
                        if (!p.IsLoaded)
                            p.Load(App.Settings);
                        App.PictureManager.CurrentProvider = p;
                    }
                }

            App.Settings.Save(App.Path + "\\settings.conf");

            if (UpdateSettings != null)
            {
                UpdateSettings(null, EventArgs.Empty);
            }
            return true;
        }

        private void SearchBoxIsKeyboardFocusedChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            UpdateSearchText();
        }

        void UpdateSearchText()
        {
            if (SearchBox.IsKeyboardFocused == false)
            {
                if (string.IsNullOrEmpty(SearchBox.Text))
                {
                    SearchBox.Text = Properties.Resources.OptionsSearchBox;
                    SearchBox.FontStyle = FontStyles.Italic;
                    SearchBox.Foreground = Brushes.Gray;
                }
            }
            else
            {
                if (SearchBox.Text == Properties.Resources.OptionsSearchBox)
                {
                    SearchBox.Text = "";
                    SearchBox.FontStyle = FontStyles.Normal;
                    SearchBox.Foreground = Brushes.Black;
                }
            }
        }
        private void SearchBoxKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && SearchBox.Text != Properties.Resources.OptionsSearchBox && SearchBox.Text.Length > 2)
            {
                App.PictureManager.GetPicture(SearchBox.Text);
            }
        }

        private void SearchBoxTextChanged(object sender, TextChangedEventArgs e)
        {
            if (SearchBox.Text != Properties.Resources.OptionsSearchBox)
            {
                SearchBox.FontStyle = FontStyles.Normal;
                SearchBox.Foreground = Brushes.Black;
            }

            ApplyButton.IsEnabled = true;
        }

        private void CheckBoxClick(object sender, RoutedEventArgs e)
        {
            ApplyButton.IsEnabled = true;
        }

        private void RefreshIntervalSliderValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            ApplyButton.IsEnabled = true;
            UpdateRefreshIntervalValueTextBlock();
        }
        private void UpdateRefreshIntervalValueTextBlock()
        {
            if (RefreshIntervalSlider == null || IMComboBox == null)
                return;
            int Invertal = 0, hours = 0, mins = 0, secs = 0;
            Invertal = (int)(((int)((TimeModes)Enum.Parse(typeof(TimeModes), (string)((ComboBoxItem)IMComboBox.SelectedValue).Content))) * RefreshIntervalSlider.Value);
            Invertal = Invertal / 1000;
            if (Invertal >= 3600)
            {
                hours = Invertal / 3600;
                Invertal = Invertal - (hours * 3600);
            }
            if (Invertal >= 60)
            {
                mins = Invertal / 60;
                Invertal = Invertal - (mins * 60);
            }
            secs = Invertal;
            RefreshIntervalValueTextBlock.Text = "";
            if (hours != 0)
                RefreshIntervalValueTextBlock.Text += hours + " " + Properties.Resources.OptionsIntervalHours + " ";
            if (mins != 0)
                RefreshIntervalValueTextBlock.Text += mins + " " + Properties.Resources.OptionsIntervalMinutes + " ";
            if (secs != 0)
                RefreshIntervalValueTextBlock.Text += secs + " " + "Sec.";
        }
        private void ClearIntervalSliderValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            ApplyButton.IsEnabled = true;

            if (ClearIntervalSlider.Value == 1)
                ClearIntervalTextBlock.Text = string.Format(Properties.Resources.OptionsClearInterval, ClearIntervalSlider.Value + " " + Properties.Resources.OptionsDay);
            else
                ClearIntervalTextBlock.Text = string.Format(Properties.Resources.OptionsClearInterval, ClearIntervalSlider.Value + " " + Properties.Resources.OptionsDays);
        }

        private void ComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ApplyButton.IsEnabled = true;
        }

        private void ClearNowButtonClick(object sender, RoutedEventArgs e)
        {
            if (Directory.Exists(App.Path + "\\Cache"))
            {
                foreach (var f in Directory.GetFiles(App.Path + "\\Cache"))
                    File.Delete(f);
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Activate();
        }

        private void ShowWarningCheckBox_Click(object sender, RoutedEventArgs e)
        {
            ApplyButton.IsEnabled = true;
        }

        private void LaunchOnStartUpCheckBox_Click(object sender, RoutedEventArgs e)
        {
            ApplyButton.IsEnabled = true;
        }

        private void IMComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ApplyButton.IsEnabled = true;
            UpdateRefreshIntervalValueTextBlock();
        }

        private void SearchBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            UpdateSearchText(); 
        }


    }
}